﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ajayumi.Platform.Core.Security
{
    /// <summary>
    /// 非对称加密算法提供者的基类
    /// </summary>
    public abstract class AsymmetricCryptoProvider : CryptoProvider
    {
        #region Properties

        /// <summary>
        /// 加密对象
        /// </summary>
        public AsymmetricAlgorithm AymAlg { get; protected set; }

        /// <summary>
        /// 公钥文件路径
        /// </summary>
        public string XmlPublicKey { get; protected set; }

        /// <summary>
        /// 私钥文件路径
        /// </summary>
        public string XmlPrivateKey { get; protected set; }

        #endregion

        protected AsymmetricCryptoProvider(string name)
            : base(name)
        {
        }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            config.Add("xmlPublicKey", SecurityConfig.XmlPublicKey);
            config.Add("xmlPrivateKey", SecurityConfig.XmlPrivateKey);

            this.XmlPublicKey = config.GetValues("xmlPublicKey")[0];
            this.XmlPrivateKey = config.GetValues("xmlPrivateKey")[0];
        }

        /// <summary>
        /// 私钥加密
        /// </summary>
        /// <param name="plainStr">需要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public abstract string EncryptByPrivateKey(string plainStr);

        /// <summary>
        /// 公钥解密
        /// </summary>
        /// <param name="encryptedStr">需要解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public abstract string DecryptByPublicKey(string encryptedStr);


        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="plainStr">待签名的字符串</param>
        /// <returns></returns>
        public abstract byte[] Sign(string plainStr);

        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="plainStr">待签名的字符串</param>
        /// <returns></returns>
        public abstract string SignToStr(string plainStr);


        /// <summary>
        /// 验证签名。
        /// </summary>
        /// <param name="plainStr">消息原文。</param>
        /// <param name="signedData">签名数据。</param>
        /// <returns>验证结果。</returns>
        public abstract bool VerifySign(string plainStr, byte[] signedData);

        /// <summary>
        /// 验证签名。
        /// </summary>
        /// <param name="plainStr">消息原文。</param>
        /// <param name="signedStr">签名数据。</param>
        /// <returns>验证结果。</returns>
        public abstract bool VerifySignFormStr(string plainStr, string signedStr);


        public override void Dispose()
        {
            this.AymAlg.Dispose();
        }
    }
}
